package com.apollographql.apollo.internal.subscription;

import com.apollographql.apollo.api.Error;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.ScalarTypeAdapters;
import com.apollographql.apollo.api.Subscription;
import com.apollographql.apollo.api.internal.Utils;
import com.apollographql.apollo.cache.normalized.Record;
import com.apollographql.apollo.cache.normalized.internal.ResponseNormalizer;
import com.apollographql.apollo.exception.ApolloNetworkException;
import com.apollographql.apollo.internal.subscription.SubscriptionManager;
import com.apollographql.apollo.response.OperationResponseParser;
import com.apollographql.apollo.subscription.OnSubscriptionManagerStateChangeListener;
import com.apollographql.apollo.subscription.OperationClientMessage;
import com.apollographql.apollo.subscription.OperationServerMessage;
import com.apollographql.apollo.subscription.SubscriptionConnectionParamsProvider;
import com.apollographql.apollo.subscription.SubscriptionManagerState;
import com.apollographql.apollo.subscription.SubscriptionTransport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import com.kt.jvm.functions.Function0;

public final class RealSubscriptionManager implements SubscriptionManager {
    static final long CONNECTION_ACKNOWLEDGE_TIMEOUT = TimeUnit.SECONDS.toMillis(5);
    static final int CONNECTION_ACKNOWLEDGE_TIMEOUT_TIMER_TASK_ID = 1;
    static final int CONNECTION_KEEP_ALIVE_TIMEOUT_TIMER_TASK_ID = 3;
    static final long INACTIVITY_TIMEOUT = TimeUnit.SECONDS.toMillis(10);
    static final int INACTIVITY_TIMEOUT_TIMER_TASK_ID = 2;
    static final String PROTOCOL_NEGOTIATION_ERROR_NOT_FOUND = "PersistedQueryNotFound";
    static final String PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED = "PersistedQueryNotSupported";
    private final boolean autoPersistSubscription;
    private final Runnable connectionAcknowledgeTimeoutTimerTask = new Runnable() {
        /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass1 */

        public void run() {
            RealSubscriptionManager.this.onConnectionAcknowledgeTimeout();
        }
    };
    private final long connectionHeartbeatTimeoutMs;
    private final Runnable connectionHeartbeatTimeoutTimerTask = new Runnable() {
        /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass3 */

        public void run() {
            RealSubscriptionManager.this.onConnectionHeartbeatTimeout();
        }
    };
    private final SubscriptionConnectionParamsProvider connectionParams;
    private final Executor dispatcher;
    private final Runnable inactivityTimeoutTimerTask = new Runnable() {
        /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass2 */

        public void run() {
            RealSubscriptionManager.this.onInactivityTimeout();
        }
    };
    private final List<OnSubscriptionManagerStateChangeListener> onStateChangeListeners = new CopyOnWriteArrayList();
    private final Function0<ResponseNormalizer<Map<String, Object>>> responseNormalizer;
    private final ScalarTypeAdapters scalarTypeAdapters;
    volatile SubscriptionManagerState state = SubscriptionManagerState.DISCONNECTED;
    Map<UUID, SubscriptionRecord> subscriptions = new LinkedHashMap();
    final AutoReleaseTimer timer = new AutoReleaseTimer();
    private final SubscriptionTransport transport;

    public RealSubscriptionManager(ScalarTypeAdapters scalarTypeAdapters2, SubscriptionTransport.Factory transportFactory, SubscriptionConnectionParamsProvider connectionParams2, Executor dispatcher2, long connectionHeartbeatTimeoutMs2, Function0<ResponseNormalizer<Map<String, Object>>> responseNormalizer2, boolean autoPersistSubscription2) {
        Utils.checkNotNull(scalarTypeAdapters2, "scalarTypeAdapters == null");
        Utils.checkNotNull(transportFactory, "transportFactory == null");
        Utils.checkNotNull(dispatcher2, "dispatcher == null");
        Utils.checkNotNull(responseNormalizer2, "responseNormalizer == null");
        this.scalarTypeAdapters = (ScalarTypeAdapters) Utils.checkNotNull(scalarTypeAdapters2, "scalarTypeAdapters == null");
        this.connectionParams = (SubscriptionConnectionParamsProvider) Utils.checkNotNull(connectionParams2, "connectionParams == null");
        this.transport = transportFactory.create(new SubscriptionTransportCallback(this, dispatcher2));
        this.dispatcher = dispatcher2;
        this.connectionHeartbeatTimeoutMs = connectionHeartbeatTimeoutMs2;
        this.responseNormalizer = responseNormalizer2;
        this.autoPersistSubscription = autoPersistSubscription2;
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public <T> void subscribe(final Subscription<?, T, ?> subscription, final Callback<T> callback) {
        Utils.checkNotNull(subscription, "subscription == null");
        Utils.checkNotNull(callback, "callback == null");
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass4 */

            public void run() {
                RealSubscriptionManager.this.doSubscribe(subscription, callback);
            }
        });
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void unsubscribe(final Subscription subscription) {
        Utils.checkNotNull(subscription, "subscription == null");
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass5 */

            public void run() {
                RealSubscriptionManager.this.doUnsubscribe(subscription);
            }
        });
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void start() {
        SubscriptionManagerState oldState;
        synchronized (this) {
            oldState = this.state;
            if (this.state == SubscriptionManagerState.STOPPED) {
                this.state = SubscriptionManagerState.DISCONNECTED;
            }
        }
        notifyStateChanged(oldState, this.state);
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void stop() {
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass6 */

            public void run() {
                RealSubscriptionManager.this.doStop();
            }
        });
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public SubscriptionManagerState getState() {
        return this.state;
    }

    /* JADX DEBUG: Multi-variable search result rejected for r0v0, resolved type: java.util.List<com.apollographql.apollo.subscription.OnSubscriptionManagerStateChangeListener> */
    /* JADX WARN: Multi-variable type inference failed */
    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void addOnStateChangeListener(OnSubscriptionManagerStateChangeListener onStateChangeListener) {
        this.onStateChangeListeners.add(Utils.checkNotNull(onStateChangeListener, "onStateChangeListener == null"));
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void removeOnStateChangeListener(OnSubscriptionManagerStateChangeListener onStateChangeListener) {
        this.onStateChangeListeners.remove(Utils.checkNotNull(onStateChangeListener, "onStateChangeListener == null"));
    }

    /* access modifiers changed from: package-private */
    public void doSubscribe(Subscription subscription, Callback callback) {
        SubscriptionManagerState oldState;
        synchronized (this) {
            oldState = this.state;
            if (!(this.state == SubscriptionManagerState.STOPPING || this.state == SubscriptionManagerState.STOPPED)) {
                this.timer.cancelTask(2);
                UUID subscriptionId = UUID.randomUUID();
                this.subscriptions.put(subscriptionId, new SubscriptionRecord(subscriptionId, subscription, callback));
                if (this.state == SubscriptionManagerState.DISCONNECTED) {
                    this.state = SubscriptionManagerState.CONNECTING;
                    this.transport.connect();
                } else if (this.state == SubscriptionManagerState.ACTIVE) {
                    this.transport.send(new OperationClientMessage.Start(subscriptionId.toString(), subscription, this.scalarTypeAdapters, this.autoPersistSubscription, false));
                }
            }
        }
        if (oldState == SubscriptionManagerState.STOPPING || oldState == SubscriptionManagerState.STOPPED) {
            callback.onError(new ApolloSubscriptionException("Illegal state: " + this.state.name() + " for subscriptions to be created. SubscriptionManager.start() must be called to re-enable subscriptions."));
        } else if (oldState == SubscriptionManagerState.CONNECTED) {
            callback.onConnected();
        }
        notifyStateChanged(oldState, this.state);
    }

    /* access modifiers changed from: package-private */
    public void doUnsubscribe(Subscription subscription) {
        synchronized (this) {
            SubscriptionRecord subscriptionRecord = null;
            for (SubscriptionRecord record : this.subscriptions.values()) {
                if (record.subscription == subscription) {
                    subscriptionRecord = record;
                }
            }
            if (subscriptionRecord != null) {
                this.subscriptions.remove(subscriptionRecord.id);
                if (this.state == SubscriptionManagerState.ACTIVE || this.state == SubscriptionManagerState.STOPPING) {
                    this.transport.send(new OperationClientMessage.Stop(subscriptionRecord.id.toString()));
                }
            }
            if (this.subscriptions.isEmpty() && this.state != SubscriptionManagerState.STOPPING) {
                startInactivityTimer();
            }
        }
    }

    /* access modifiers changed from: package-private */
    public void doStop() {
        SubscriptionManagerState oldState;
        Collection<SubscriptionRecord> subscriptionRecords;
        synchronized (this) {
            oldState = this.state;
            this.state = SubscriptionManagerState.STOPPING;
            subscriptionRecords = this.subscriptions.values();
            if (oldState == SubscriptionManagerState.ACTIVE) {
                for (SubscriptionRecord subscriptionRecord : subscriptionRecords) {
                    this.transport.send(new OperationClientMessage.Stop(subscriptionRecord.id.toString()));
                }
            }
            this.state = SubscriptionManagerState.STOPPED;
            this.transport.disconnect(new OperationClientMessage.Terminate());
            this.subscriptions = new LinkedHashMap();
        }
        for (SubscriptionRecord record : subscriptionRecords) {
            record.notifyOnCompleted();
        }
        notifyStateChanged(oldState, SubscriptionManagerState.STOPPING);
        notifyStateChanged(SubscriptionManagerState.STOPPING, this.state);
    }

    /* access modifiers changed from: package-private */
    public void onTransportConnected() {
        SubscriptionManagerState oldState;
        Collection<SubscriptionRecord> subscriptionRecords = new ArrayList<>();
        synchronized (this) {
            oldState = this.state;
            if (this.state == SubscriptionManagerState.CONNECTING) {
                subscriptionRecords.addAll(this.subscriptions.values());
                this.state = SubscriptionManagerState.CONNECTED;
                this.transport.send(new OperationClientMessage.Init(this.connectionParams.provide()));
            }
            if (this.state == SubscriptionManagerState.CONNECTED) {
                this.timer.schedule(1, this.connectionAcknowledgeTimeoutTimerTask, CONNECTION_ACKNOWLEDGE_TIMEOUT);
            }
        }
        for (SubscriptionRecord record : subscriptionRecords) {
            record.callback.onConnected();
        }
        notifyStateChanged(oldState, this.state);
    }

    /* access modifiers changed from: package-private */
    public void onConnectionAcknowledgeTimeout() {
        this.timer.cancelTask(1);
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass7 */

            public void run() {
                RealSubscriptionManager.this.onTransportFailure(new ApolloNetworkException("Subscription server is not responding"));
            }
        });
    }

    /* access modifiers changed from: package-private */
    public void onInactivityTimeout() {
        this.timer.cancelTask(2);
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AnonymousClass8 */

            public void run() {
                RealSubscriptionManager.this.disconnect(false);
            }
        });
    }

    /* access modifiers changed from: package-private */
    public void onTransportFailure(Throwable t) {
        for (SubscriptionRecord record : disconnect(true)) {
            record.notifyOnNetworkError(t);
        }
    }

    /* access modifiers changed from: package-private */
    public void onOperationServerMessage(OperationServerMessage message) {
        if (message instanceof OperationServerMessage.ConnectionAcknowledge) {
            onConnectionAcknowledgeServerMessage();
        } else if (message instanceof OperationServerMessage.Data) {
            onOperationDataServerMessage((OperationServerMessage.Data) message);
        } else if (message instanceof OperationServerMessage.Error) {
            onErrorServerMessage((OperationServerMessage.Error) message);
        } else if (message instanceof OperationServerMessage.Complete) {
            onCompleteServerMessage((OperationServerMessage.Complete) message);
        } else if (message instanceof OperationServerMessage.ConnectionError) {
            disconnect(true);
        } else if (message instanceof OperationServerMessage.ConnectionKeepAlive) {
            resetConnectionKeepAliveTimerTask();
        }
    }

    /* access modifiers changed from: package-private */
    public Collection<SubscriptionRecord> disconnect(boolean force) {
        SubscriptionManagerState oldState;
        Collection<SubscriptionRecord> subscriptionRecords;
        synchronized (this) {
            oldState = this.state;
            subscriptionRecords = this.subscriptions.values();
            if (force || this.subscriptions.isEmpty()) {
                this.transport.disconnect(new OperationClientMessage.Terminate());
                this.state = this.state == SubscriptionManagerState.STOPPING ? SubscriptionManagerState.STOPPED : SubscriptionManagerState.DISCONNECTED;
                this.subscriptions = new LinkedHashMap();
            }
        }
        notifyStateChanged(oldState, this.state);
        return subscriptionRecords;
    }

    @Override // com.apollographql.apollo.internal.subscription.SubscriptionManager
    public void reconnect() {
        SubscriptionManagerState oldState;
        synchronized (this) {
            oldState = this.state;
            this.state = SubscriptionManagerState.DISCONNECTED;
            this.transport.disconnect(new OperationClientMessage.Terminate());
            this.state = SubscriptionManagerState.CONNECTING;
            this.transport.connect();
        }
        notifyStateChanged(oldState, SubscriptionManagerState.DISCONNECTED);
        notifyStateChanged(SubscriptionManagerState.DISCONNECTED, SubscriptionManagerState.CONNECTING);
    }

    /* access modifiers changed from: package-private */
    public void onConnectionHeartbeatTimeout() {
        reconnect();
    }

    /* access modifiers changed from: package-private */
    public void onConnectionClosed() {
        SubscriptionManagerState oldState;
        Collection<SubscriptionRecord> subscriptionRecords;
        synchronized (this) {
            oldState = this.state;
            subscriptionRecords = this.subscriptions.values();
            this.state = SubscriptionManagerState.DISCONNECTED;
            this.subscriptions = new LinkedHashMap();
        }
        for (SubscriptionRecord record : subscriptionRecords) {
            record.callback.onTerminated();
        }
        notifyStateChanged(oldState, this.state);
    }

    private void resetConnectionKeepAliveTimerTask() {
        if (this.connectionHeartbeatTimeoutMs > 0) {
            synchronized (this) {
                this.timer.schedule(3, this.connectionHeartbeatTimeoutTimerTask, this.connectionHeartbeatTimeoutMs);
            }
        }
    }

    private void startInactivityTimer() {
        this.timer.schedule(2, this.inactivityTimeoutTimerTask, INACTIVITY_TIMEOUT);
    }

    private void onOperationDataServerMessage(OperationServerMessage.Data message) {
        SubscriptionRecord subscriptionRecord;
        String subscriptionId = message.id != null ? message.id : "";
        synchronized (this) {
            try {
                subscriptionRecord = this.subscriptions.get(UUID.fromString(subscriptionId));
            } catch (IllegalArgumentException e) {
                subscriptionRecord = null;
            }
        }
        if (subscriptionRecord != null) {
            ResponseNormalizer<Map<String, Object>> normalizer = this.responseNormalizer.invoke();
            try {
                subscriptionRecord.notifyOnResponse(new OperationResponseParser(subscriptionRecord.subscription, subscriptionRecord.subscription.responseFieldMapper(), this.scalarTypeAdapters, normalizer).parse(message.payload), normalizer.records());
            } catch (Exception e2) {
                SubscriptionRecord subscriptionRecord2 = removeSubscriptionById(subscriptionId);
                if (subscriptionRecord2 != null) {
                    subscriptionRecord2.notifyOnError(new ApolloSubscriptionException("Failed to parse server message", e2));
                }
            }
        }
    }

    private void onConnectionAcknowledgeServerMessage() {
        SubscriptionManagerState oldState;
        synchronized (this) {
            oldState = this.state;
            this.timer.cancelTask(1);
            if (this.state == SubscriptionManagerState.CONNECTED) {
                this.state = SubscriptionManagerState.ACTIVE;
                for (SubscriptionRecord subscriptionRecord : this.subscriptions.values()) {
                    this.transport.send(new OperationClientMessage.Start(subscriptionRecord.id.toString(), subscriptionRecord.subscription, this.scalarTypeAdapters, this.autoPersistSubscription, false));
                }
            }
        }
        notifyStateChanged(oldState, this.state);
    }

    private void onErrorServerMessage(OperationServerMessage.Error message) {
        boolean resendSubscriptionWithDocument;
        SubscriptionRecord subscriptionRecord = removeSubscriptionById(message.id != null ? message.id : "");
        if (subscriptionRecord != null) {
            if (this.autoPersistSubscription) {
                Error error = OperationResponseParser.parseError(message.payload);
                resendSubscriptionWithDocument = PROTOCOL_NEGOTIATION_ERROR_NOT_FOUND.equalsIgnoreCase(error.getMessage()) || PROTOCOL_NEGOTIATION_ERROR_NOT_SUPPORTED.equalsIgnoreCase(error.getMessage());
            } else {
                resendSubscriptionWithDocument = false;
            }
            if (resendSubscriptionWithDocument) {
                synchronized (this) {
                    this.subscriptions.put(subscriptionRecord.id, subscriptionRecord);
                    this.transport.send(new OperationClientMessage.Start(subscriptionRecord.id.toString(), subscriptionRecord.subscription, this.scalarTypeAdapters, true, true));
                }
                return;
            }
            subscriptionRecord.notifyOnError(new ApolloSubscriptionServerException(message.payload));
        }
    }

    private void onCompleteServerMessage(OperationServerMessage.Complete message) {
        SubscriptionRecord subscriptionRecord = removeSubscriptionById(message.id != null ? message.id : "");
        if (subscriptionRecord != null) {
            subscriptionRecord.notifyOnCompleted();
        }
    }

    private SubscriptionRecord removeSubscriptionById(String subscriptionId) {
        SubscriptionRecord subscriptionRecord;
        synchronized (this) {
            try {
                subscriptionRecord = this.subscriptions.remove(UUID.fromString(subscriptionId));
            } catch (IllegalArgumentException e) {
                subscriptionRecord = null;
            }
            if (this.subscriptions.isEmpty()) {
                startInactivityTimer();
            }
        }
        return subscriptionRecord;
    }

    private void notifyStateChanged(SubscriptionManagerState oldState, SubscriptionManagerState newState) {
        if (oldState != newState) {
            for (OnSubscriptionManagerStateChangeListener onStateChangeListener : this.onStateChangeListeners) {
                onStateChangeListener.onStateChange(oldState, newState);
            }
        }
    }

    /* access modifiers changed from: private */
    public static class SubscriptionRecord {
        final Callback<?> callback;
        final UUID id;
        final Subscription<?, ?, ?> subscription;

        SubscriptionRecord(UUID id2, Subscription<?, ?, ?> subscription2, Callback<?> callback2) {
            this.id = id2;
            this.subscription = subscription2;
            this.callback = callback2;
        }

        /* access modifiers changed from: package-private */
        public void notifyOnResponse(Response response, Collection<Record> cacheRecords) {
            this.callback.onResponse(new SubscriptionResponse<>(this.subscription, response, cacheRecords));
        }

        /* access modifiers changed from: package-private */
        public void notifyOnError(ApolloSubscriptionException error) {
            this.callback.onError(error);
        }

        /* access modifiers changed from: package-private */
        public void notifyOnNetworkError(Throwable t) {
            this.callback.onNetworkError(t);
        }

        /* access modifiers changed from: package-private */
        public void notifyOnCompleted() {
            this.callback.onCompleted();
        }
    }

    private static final class SubscriptionTransportCallback implements SubscriptionTransport.Callback {
        private final RealSubscriptionManager delegate;
        private final Executor dispatcher;

        SubscriptionTransportCallback(RealSubscriptionManager delegate2, Executor dispatcher2) {
            this.delegate = delegate2;
            this.dispatcher = dispatcher2;
        }

        @Override // com.apollographql.apollo.subscription.SubscriptionTransport.Callback
        public void onConnected() {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.SubscriptionTransportCallback.AnonymousClass1 */

                public void run() {
                    SubscriptionTransportCallback.this.delegate.onTransportConnected();
                }
            });
        }

        @Override // com.apollographql.apollo.subscription.SubscriptionTransport.Callback
        public void onFailure(final Throwable t) {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.SubscriptionTransportCallback.AnonymousClass2 */

                public void run() {
                    SubscriptionTransportCallback.this.delegate.onTransportFailure(t);
                }
            });
        }

        @Override // com.apollographql.apollo.subscription.SubscriptionTransport.Callback
        public void onMessage(final OperationServerMessage message) {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.SubscriptionTransportCallback.AnonymousClass3 */

                public void run() {
                    SubscriptionTransportCallback.this.delegate.onOperationServerMessage(message);
                }
            });
        }

        @Override // com.apollographql.apollo.subscription.SubscriptionTransport.Callback
        public void onClosed() {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.SubscriptionTransportCallback.AnonymousClass4 */

                public void run() {
                    SubscriptionTransportCallback.this.delegate.onConnectionClosed();
                }
            });
        }
    }

    /* access modifiers changed from: package-private */
    public static final class AutoReleaseTimer {
        final Map<Integer, TimerTask> tasks = new LinkedHashMap();
        Timer timer;

        AutoReleaseTimer() {
        }

        /* access modifiers changed from: package-private */
        public void schedule(final int taskId, final Runnable task, long delay) {
            TimerTask timerTask = new TimerTask() {
                /* class com.apollographql.apollo.internal.subscription.RealSubscriptionManager.AutoReleaseTimer.AnonymousClass1 */

                public void run() {
                    try {
                        task.run();
                    } finally {
                        AutoReleaseTimer.this.cancelTask(taskId);
                    }
                }
            };
            synchronized (this) {
                TimerTask previousTimerTask = this.tasks.put(Integer.valueOf(taskId), timerTask);
                if (previousTimerTask != null) {
                    previousTimerTask.cancel();
                }
                if (this.timer == null) {
                    this.timer = new Timer("Subscription SmartTimer", true);
                }
                this.timer.schedule(timerTask, delay);
            }
        }

        /* access modifiers changed from: package-private */
        public void cancelTask(int taskId) {
            synchronized (this) {
                TimerTask timerTask = this.tasks.remove(Integer.valueOf(taskId));
                if (timerTask != null) {
                    timerTask.cancel();
                }
                if (this.tasks.isEmpty() && this.timer != null) {
                    this.timer.cancel();
                    this.timer = null;
                }
            }
        }
    }
}
